package ar.com.nexoweb.actualidadbasquet;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import ar.com.nexoweb.actualidadbasquet.adapters.SuperbasquetAdapter;
import ar.com.nexoweb.actualidadbasquet.data.AsyncTaskCompletionListener;
import ar.com.nexoweb.actualidadbasquet.entities.Noticia;
import ar.com.nexoweb.actualidadbasquet.network.RssFeedAsyncTask;
import ar.com.nexoweb.actualidadbasquet.utility.Utility;

public class ListadoSuperbasquetActivity extends Activity implements AsyncTaskCompletionListener {
	private RelativeLayout layout;
	private ListView listview;
	private ImageView btnRecargar;
	private TextView txtTitulo;
	Context ctx;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.item_listado_rss);
		
		layout = (RelativeLayout) findViewById(R.id.layoutListado);
		layout.setBackgroundResource(R.drawable.fondo_superbasquet);
		
		ctx = getApplicationContext();
		listview = (ListView) findViewById(R.id.rssfeed_listview);
		txtTitulo = (TextView) findViewById(R.id.txtTituloRSS);
		
		txtTitulo.setText("Super Basquet");
		
		btnRecargar = (ImageView) findViewById(R.id.imgRecargar);
		btnRecargar.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				actualizarFeed();
			}
		});
		
		actualizarFeed();
		
	}

	@Override
	public void onTaskComplete(List<Noticia> result) {
		final SuperbasquetAdapter _adapter= new SuperbasquetAdapter(ListadoSuperbasquetActivity.this,
				result);
		listview.setAdapter(_adapter);
		
		listview.setOnItemClickListener( new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Noticia noti = (Noticia) _adapter.getItem(position);

				Toast.makeText(getApplicationContext(), noti.getTitle(),
						Toast.LENGTH_SHORT).show();
				
				Intent intent = new Intent();
				intent.setClass(view.getContext(), SuperbasquetActivity.class);
				intent.putExtra("noticia", noti);
				startActivity(intent);
				
			}
		});
	}
	
	private void actualizarFeed() {
		if(Utility.determineConnectivity(ListadoSuperbasquetActivity.this))
			new RssFeedAsyncTask(this).execute(Utility.urlSuperbasquet);
		else
			Toast.makeText(this, "No hay conexión a internet", Toast.LENGTH_SHORT).show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.noticias, menu);
		return true;
	}

}
